<template>
  <div class="container">
    <div class="contents">
      <div class="title_bar">
        <div class="close-area" @click="close">
          <img src="/assets/close.png" alt="" />
        </div>
        <div class="title">手写签名</div>
      </div>

      <div class="canvas_content" ref="canvasContent">
        <canvas class="canvas" ref="canvas" @touchmove="move" @touchstart="start" @touchend="end" @touchcancel="cancel"></canvas>
        <div class="canvas-tip" v-show="!startSign">请 在 此 处 签 名</div>
      </div>
      <div class="action_bar">
        <div class="bar-1">
          <div class="tip">此服务能力由福建正孚软件有限公司提供</div>
          <template v-if="confirmLoading">
            <div class="area">
              <div class="btn btn-reset">重写</div>
              <div class="btn btn-ok">确认中 ...</div>
            </div>
          </template>
          <template v-else>
            <div class="area" :class="{ signed: startSign }">
              <div class="btn btn-reset" @click="rewrite">重写</div>
              <div class="btn btn-ok" @click="saveSign">确认</div>
            </div>
          </template>
        </div>
        <div class="bar-2"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { utils } from '@/utils/util'
import { completeSigningWithError } from '@cis/mybmw-bridge-digital-signature'
import { useFunctional } from '@/utils/useHooks'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

let { message, dialog } = useFunctional()
let canvas = ref()
let canvasContent = ref()
let context = ref()
let canvasMoveUse = ref()
let startSign = ref(false)

function close() {
  // router.go(-1)
  completeSigningWithError({ reason: 'cancel' })
}

function initCanvas() {
  canvas.value.width = canvasContent.value.clientWidth
  canvas.value.height = canvasContent.value.clientHeight
  context.value = canvas.value.getContext('2d') // 设置2D渲染区域
  context.value.strokeStyle = '#000'
  context.value.lineWidth = 5 // 设置线的宽度
  context.value.lineCap = 'round'
  context.value.lineJoin = 'round'
}

// 画布的触摸移动开始手势响应
function start(e) {
  const canvasX = e.targetTouches[0].clientX - canvas.value.getBoundingClientRect().left
  const canvasY = e.targetTouches[0].clientY - canvas.value.getBoundingClientRect().top
  context.value.beginPath() // 移动的起点
  context.value.moveTo(canvasY, canvas.value.height - canvasX)
  canvasMoveUse.value = true
  // 标识开始签名
  startSign.value = true
}

// 画布的触摸移动手势响应
function move(e) {
  // 只在移动是进行绘制图线
  if (canvasMoveUse.value) {
    const canvasX = e.targetTouches[0].clientX - canvas.value.getBoundingClientRect().left
    const canvasY = e.targetTouches[0].clientY - canvas.value.getBoundingClientRect().top
    context.value.lineTo(canvasY, canvas.value.height - canvasX)
    context.value.stroke()
  }
}
// 画布的触摸移动结束手势响应
function end() {
  canvasMoveUse.value = false
}

// 画布的触摸取消响应
function cancel(e) {
  canvasMoveUse.value = false
}

// 重写
function rewrite() {
  context.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
  startSign.value = false
}

let imageBase64 = ref()

// 保存
function saveSign() {
  if (startSign.value) {
    dialog({
      horizontal: true, // 横屏效果
      iconType: 'warning',
      title: '提示',
      text: '请用正楷签署您的姓名，避免错别字或过于潦草导致无法律效力。签名一旦提交，将无法更改，请认真核对。',
      confirmButtonText: '确认签署',
      cancelButtonText: '返回',
      confirmCallback,
    })
    imageBase64.value = canvas.value.toDataURL()
  } else {
    message('请完成签名!', 'horizontal')
  }
}

let confirmLoading = ref(false)
function confirmCallback() {
  console.log('请求签署')
  confirmLoading.value = true
  setTimeout(() => {
    message('完成签名!', 'horizontal')
    confirmLoading.value = false
  }, 2000)
}

// confirm: function () {
//   if (this.confirmLoading) return
//   this.confirmLoading = true
//   let name = new Date().getTime(),
//     file = utils.dataURLtoFile(this.imageBase64, name + '.png'),
//     index = this.imageBase64.indexOf(','),
//     result = this.imageBase64.slice(index + 1),
//     params = {
//       name: file.name,
//       type: 4,
//       suffix: 'png',
//       size: Number(utils.accDiv(utils.accDiv(file.size, 1024), 1024).toFixed(4)),
//       base64: result,
//     }
// },

onMounted(() => {
  initCanvas()
  nextTick(rewrite)
})
</script>

<style scoped lang="scss">
.canvas {
  touch-action: none;
}
.container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  .contents {
    width: 100vh;
    height: 100vw;
    animation: rotate 0.1s forwards;
    transform-origin: 50vw 50vw;

    .title_bar {
      height: 48px;
      font-size: 20px;
      text-align: center;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .close-area {
        position: absolute;
        top: 0;
        left: 0;
        width: 48px;
        height: 48px;
        // background-color: pink;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 10px;
          height: 10px;
          display: block;
        }
      }
      .title {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: black;
        font-weight: 700;
      }
    }

    .canvas_content {
      width: 100%;
      height: calc(100vw - 48px - 44px - 20px);
      canvas {
        background-color: white;
      }
      .canvas-tip {
        pointer-events: none;
        position: absolute;
        width: 100%;
        top: 50%;
        left: 50%;
        text-align: center;
        transform: translate(-50%, -50%);
        color: rgba(242, 242, 242, 1);
        font-size: 60px;
        font-weight: 400;
      }
    }

    .action_bar {
      padding: 0 20px;
      // background-color: pink;
      .bar-1 {
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .tip {
          color: rgba(0, 0, 0, 0.6);
          font-size: 12px;
        }
        .area {
          display: flex;
          align-items: center;
          .btn {
            transition: all var(--transition-time);
            display: flex;
            align-items: center;
            justify-content: center;
            width: 120px;
            height: 44px;
            border-radius: 2px;
            font-size: 14px;
          }
          .btn-reset {
            color: rgba(153, 153, 153, 1);
          }
          .btn-ok {
            color: white;
            background-color: rgba(153, 153, 153, 1);
          }
        }
        .signed {
          .btn-reset {
            background-color: white;
            color: rgba(0, 0, 0, 1);
          }
          .btn-ok {
            color: white;
            background-color: rgba(0, 0, 0, 1);
          }
        }
      }
      .bar-2 {
        height: 20px;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(90deg);
  }
}
</style>
